package com.czy.daishusys.ui.message;

import android.content.Intent;
import android.graphics.Color;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.czy.daishusys.R;

import com.czy.daishusys.ui.MainActivity;
import com.czy.daishusys.utils.MyLog;
import com.easemob.cases.db.MessageDBHelper;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMConversation.EMConversationType;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.model.EaseAtMessageHelper;
import com.hyphenate.easeui.ui.EaseConversationListFragment;
import com.hyphenate.easeui.widget.EaseConversationList;
import com.hyphenate.easeui.widget.EaseConversationList.EaseConversationListHelper;
import com.hyphenate.util.NetUtils;

import libs.SwipeMenu;
import libs.SwipeMenuCreator;
import libs.SwipeMenuItem;

public class ConversationFragment extends EaseConversationListFragment {

    private TextView errorText;


    private SwipeMenuCreator creator;

    private final int SWIPE_MENU_ITEM_BUTTON_DELETE = 1;
    private final int SWIPE_MENU_ITEM_BUTTON_TOP = 0;
    private View errorView = null;
    private boolean isShowError = false;

    @Override
    protected void initView() {
        super.initView();
        errorView = (LinearLayout) View.inflate(getActivity(), R.layout.em_chat_neterror_item, null);
        errorItemContainer.addView(errorView);
        View tipsView = (LinearLayout) View.inflate(getActivity(), R.layout.item_message_tips, null);
        conversationTipsContainer.addView(tipsView);
        errorText = (TextView) errorView.findViewById(R.id.tv_connect_errormsg);
    }

    @Override
    protected void setUpView() {
        super.setUpView();
        // register context menu
        registerForContextMenu(conversationListView);

        titleBar.setVisibility(View.GONE);
        searchBar.setVisibility(View.GONE);

        creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                int type = menu.getViewType();
                SwipeMenuItem topItem = new SwipeMenuItem(getContext());
                topItem.setBackground(R.color.swipe_gary_bg);
                if ((type >> 1 & 0b1) == 1) {
                    topItem.setWidth(dp2px(100));
                    topItem.setTitle("取消置顶");
                } else {
                    topItem.setWidth(dp2px(67));
                    topItem.setTitle("置顶");
                }
                topItem.setTitleSize(18);
                topItem.setTitleColor(Color.WHITE);
                topItem.setId(SWIPE_MENU_ITEM_BUTTON_TOP);
                menu.addRightMenuItem(topItem);
                SwipeMenuItem deleteItem = new SwipeMenuItem(getContext());
                deleteItem.setBackground(R.color.swipe_red_bg);
                deleteItem.setWidth(dp2px(67));
                deleteItem.setTitle("删除");
                deleteItem.setTitleSize(18);
                deleteItem.setTitleColor(Color.WHITE);
                deleteItem.setId(SWIPE_MENU_ITEM_BUTTON_DELETE);
                menu.addRightMenuItem(deleteItem);
            }
        };
        conversationListView.setMenuCreator(creator);
        conversationListView.setOpenInterpolator(new BounceInterpolator());
        conversationListView.setCloseInterpolator(new BounceInterpolator());
        conversationListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                EMConversation conversation = conversationListView.getItem(position);
                String username = conversation.conversationId();


                if (username.equals(EMClient.getInstance().getCurrentUser()))
                    Toast.makeText(getActivity(), getString(R.string.Cant_chat_with_yourself), Toast.LENGTH_SHORT).show();
                else {
                    // start chat acitivity
                    Intent intent = new Intent(getActivity(), ChatActivity.class);
                    if (conversation.isGroup()) {
                        if (conversation.getType() == EMConversation.EMConversationType.ChatRoom) {
                            // it's group chat
                            //intent.putExtra(Constants.EXTRA_CHAT_TYPE, Constants.CHATTYPE_CHATROOM);
                        } else {
                            intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_GROUP);
                        }

                    }

                    // it's single chat
                    intent.putExtra(EaseConstant.EXTRA_USER_ID, username);
                    startActivity(intent);
                }
            }
        });


        conversationListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MyLog.e("yang", "aaaaaaaaaaaaaaa");
                EMConversation conversation = conversationListView.getItem(position);
                String username = conversation.conversationId();
                if (username.equals(EMClient.getInstance().getCurrentUser()))
                    Toast.makeText(getActivity(), getString(R.string.Cant_chat_with_yourself), Toast.LENGTH_SHORT).show();
                else {
                    // start chat acitivity
                    Intent intent = new Intent(getActivity(), ChatActivity.class);
                    if (conversation.isGroup()) {
                        if (conversation.getType() == EMConversationType.ChatRoom) {
                            // it's group chat
                            //intent.putExtra(Constants.EXTRA_CHAT_TYPE, Constants.CHATTYPE_CHATROOM);
                        } else {
                            intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_GROUP);
                        }

                    }
                    // it's single chat
                    intent.putExtra(EaseConstant.EXTRA_USER_ID, username);

                    startActivity(intent);
                }
            }
        });
        conversationListView.setOnMenuItemClickListener(new EaseConversationList.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, boolean isRightMenu, SwipeMenu menu, SwipeMenuItem item) {
                EMConversation conversation = conversationListView.getItem(position);
                switch (item.getId()) {
                    case SWIPE_MENU_ITEM_BUTTON_TOP:
                        if ("TOP".equals(conversation.getExtField())) {
                            conversation.setExtField("");
                        } else {
                            conversation.setExtField("TOP");
                        }
                        break;
                    case SWIPE_MENU_ITEM_BUTTON_DELETE:
                        if (conversation.getType() == EMConversation.EMConversationType.GroupChat) {
                            EaseAtMessageHelper.get().removeAtMeGroup(conversation.conversationId());
                        }
                        try {
                            // delete conversation
                            EMClient.getInstance().chatManager().deleteConversation(conversation.conversationId(), false);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;

                }
                refresh();
                return false;
            }
        });
        //red packet code : 红包回执消息在会话列表最后一条消息的展示
        conversationListView.setConversationListHelper(new EaseConversationListHelper() {
            @Override
            public String onSetItemSecondaryText(EMMessage lastMessage) {
                /*if (lastMessage.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, false)) {
                    String sendNick = lastMessage.getStringAttribute(RedPacketConstant.EXTRA_RED_PACKET_SENDER_NAME, "");
                    String receiveNick = lastMessage.getStringAttribute(RedPacketConstant.EXTRA_RED_PACKET_RECEIVER_NAME, "");
                    String msg;
                    if (lastMessage.direct() == EMMessage.Direct.RECEIVE) {
                        msg = String.format(getResources().getString(R.string.msg_someone_take_red_packet), receiveNick);
                    } else {
                        if (sendNick.equals(receiveNick)) {
                            msg = getResources().getString(R.string.msg_take_red_packet);
                        } else {
                            msg = String.format(getResources().getString(R.string.msg_take_someone_red_packet), sendNick);
                        }
                    }
                    return msg;
                }*/
                return null;
            }
        });
        //super.setUpView();
        //end of red packet code
        //setListMarginBottom();
    }

    @Override
    protected void onConnectionDisconnected() {
        super.onConnectionDisconnected();
        if (NetUtils.hasNetwork(getActivity())) {
            errorText.setText(R.string.can_not_connect_chat_server_connection);
        } else {
            errorText.setText(R.string.the_current_network);
        }

    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        getActivity().getMenuInflater().inflate(R.menu.em_delete_message, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        boolean deleteMessage = false;
        if (item.getItemId() == R.id.delete_message) {
            deleteMessage = true;
        } else if (item.getItemId() == R.id.delete_conversation) {
            deleteMessage = false;
        }
        EMConversation tobeDeleteCons = conversationListView.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position);
        if (tobeDeleteCons == null) {
            return true;
        }
        if (tobeDeleteCons.getType() == EMConversationType.GroupChat) {
            EaseAtMessageHelper.get().removeAtMeGroup(tobeDeleteCons.conversationId());
        }
        try {
            // delete conversation
            EMClient.getInstance().chatManager().deleteConversation(tobeDeleteCons.conversationId(), deleteMessage);
            MessageDBHelper.getInstance().deleteMessage(tobeDeleteCons.conversationId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        refresh();

        //TODO update unread count
        //((MainActivity) getActivity()).updateUnreadLabel();
        return true;
    }

    /* 调整RecyclerView与底部的距离,防页面内容被TAB遮挡 */
    private void setListMarginBottom() {
        /*int height = 0;
        if ((int) SharedPreferencesUtils.getParam(getActivity(), UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) != 0) {
            Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.main_tab_bottom_bg);
            height = mBitmap.getHeight();
        } else {
            if (getActivity() != null) {
                LinearLayout llWrapper = (LinearLayout) getActivity().findViewById(R.id.ll_bind_store_tab_wrapper);
                if (llWrapper != null) {
                    int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
                    int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
                    llWrapper.measure(w, h);
                    height = llWrapper.getMeasuredHeight();
                }
            }
        }
        LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
        layoutParam.bottomMargin = height;
        //conversationListView.setLayoutParams(layoutParam);*/
    }


    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }


    //TODO 网络切换

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
